package br.com.gerenciarmembros.client;

import br.com.gerenciarmembros.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class GerenciamentoMembros implements EntryPoint {
	
	private VerticalPanel mainPanel = new VerticalPanel();
  	private FlexTable membrosCadastrados = new FlexTable();
  	private HorizontalPanel addPanel = new HorizontalPanel();
  	private TextBox novoMembro = new TextBox();
  	private Button addMembro = new Button("Add");
  	private Label lastUpdatedLabel = new Label();

  	@Override
	public void onModuleLoad() {
		membrosCadastrados.setText(0, 0, "Nome       ");
		membrosCadastrados.setText(0, 1, "Telefone   ");
		membrosCadastrados.setText(0, 2, "Atividades ");
		
		addPanel.add(novoMembro);
		addPanel.add(addMembro);
		
		mainPanel.add(membrosCadastrados);
		mainPanel.add(addPanel);
		mainPanel.add(lastUpdatedLabel);
		
		RootPanel.get("membrosCadastrados").add(mainPanel);
		novoMembro.setFocus(true);
		
		addMembro.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				adicionarMembro();
			}
		});
		
		novoMembro.addKeyPressHandler(new KeyPressHandler() {
			public void onKeyPress(KeyPressEvent event) {
				if (event.getCharCode() == KeyCodes.KEY_ENTER) {
			          adicionarMembro();
			        }
			}
		});
	}
  	
	private void adicionarMembro() {
		final String nome = novoMembro.getText().toUpperCase().trim();
		novoMembro.setFocus(true);
		
		if (!nome.matches("^[0-9A-Z\\.]{1,10}$")){
			Window.alert("'" + nome + "' is not a valid symbol.");
			novoMembro.selectAll();
			return;
		}
		
		int row = membrosCadastrados.getRowCount();
	    membrosCadastrados.setText(row, 0, novoMembro.getText());
		
		novoMembro.setText("");
	}
}
